﻿namespace SolidMvvm {
	using System;
	using System.ComponentModel;
	using System.Windows;

	public class WPFDialog : PropertyChangedNotifier, IDisposable {
		public delegate void CloseRequestedDelegate(WPFDialog sender);

		Window window;

		public WPFDialog(bool sizeToContent, CloseRequestedDelegate closeRequestedDelegate) {
			window = new Window { WindowStyle = WindowStyle.ThreeDBorderWindow, SizeToContent = sizeToContent ? SizeToContent.WidthAndHeight : SizeToContent.Manual, ResizeMode = ResizeMode.CanResizeWithGrip, ShowInTaskbar = false, WindowStartupLocation = WindowStartupLocation.CenterOwner };
			window.Closing += window_Closing;
			CloseRequested = closeRequestedDelegate;
		}

		public object Content
		{
			get
			{
				return window.Content;
			}
			set
			{
				if (window.Content == value)
					return;

				window.Content = value;
				RaisePropertyChanged(() => Content);
			}
		}

		public string Title
		{
			get
			{
				return window.Title;
			}
			set
			{
				if (window.Title == value)
					return;

				window.Title = value;
				RaisePropertyChanged(() => Title);
			}
		}

		public CloseRequestedDelegate CloseRequested { get; private set; }

		public void Dispose() {
			if (window != null) {
				window.Closing -= window_Closing;
				window.Content = null;
				window.Close();
			}
			window = null;

			CloseRequested = null;
		}

		void window_Closing(object sender, CancelEventArgs e) {
			e.Cancel = true;

			Dispatcher.BeginInvoke((Action)(() => CloseRequested(this)));
		}

		public bool? ShowDialog(Window ownerWindow) {
			window.Owner = ownerWindow;
			return window.ShowDialog();
		}
	}
}
